package com.wsd.jing.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsd.jing.constant.SystemConstant;
import com.wsd.jing.entity.Menu;
import com.wsd.jing.entity.RoleMenu;
import com.wsd.jing.enums.CodeEnum;
import com.wsd.jing.exception.BusinessException;
import com.wsd.jing.mapper.MenuMapper;
import com.wsd.jing.mapper.RoleMenuMapper;
import com.wsd.jing.request.CommonRequest;
import com.wsd.jing.service.IMenuService;
import com.wsd.jing.utils.SortUtil;
import com.wsd.jing.vo.AuthVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * All rights Reserved, Designed By www.tom.com
 *
 * @author tom
 * @version 1.0.0
 * @projectName: jing
 * @packageName: com.wsd.jing.service.impl
 * @className: MenuServiceImpl
 * @description: 菜单服务实现类
 * @createDate 2022-11-20 07:41
 * @copyright 2022-11-20 07:41 www.tom.com Inc. All rights reserved.
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    private final MenuMapper menuMapper;
    private final RoleMenuMapper roleMenuMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertMenu(Menu menu) {
        menu.setCreateTime(LocalDateTime.now());
        return this.save(menu);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMenu(Menu menu) {
        menu.setUpdateTime(LocalDateTime.now());
        return this.updateById(menu);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteMenu(Integer id) {
        QueryWrapper<RoleMenu> roleMenuQueryWrapper = new QueryWrapper<>();
        roleMenuQueryWrapper.lambda().eq(RoleMenu::getMenuId, id);
        List<RoleMenu> roleMenuList = roleMenuMapper.selectList(roleMenuQueryWrapper);
        if (CollectionUtil.isNotEmpty(roleMenuList)) {
            throw new BusinessException(CodeEnum.MENU_NOT_DELETE);
        }
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteMenus(String ids) {
        List<String> idList = StrUtil.splitTrim(ids, ",");
        QueryWrapper<RoleMenu> roleMenuQueryWrapper = new QueryWrapper<>();
        roleMenuQueryWrapper.lambda().in(RoleMenu::getMenuId, idList);
        List<RoleMenu> roleMenuList = roleMenuMapper.selectList(roleMenuQueryWrapper);
        if (CollectionUtil.isNotEmpty(roleMenuList)) {
            throw new BusinessException(CodeEnum.MENU_NOT_DELETE);
        }
        return this.removeByIds(idList);
    }

    @Override
    public Menu getMenu(Integer id) {
        return this.getById(id);
    }

    @Override
    public List<Menu> listMenus(CommonRequest commonRequest, Menu menu) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        // TODO 设置查询条件

        // 处理排序字段
        SortUtil.handleListSort(commonRequest, queryWrapper);
        return this.list(queryWrapper);
    }

    @Override
    public Map<String, Object> listPageMenus(CommonRequest commonRequest, Menu menu) {
        Map<String, Object> resultMap = new HashMap<>(2);
        Page<Menu> page = new Page<>(commonRequest.getPageNum(), commonRequest.getPageSize());
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        // TODO 设置查询条件
        if (StrUtil.isNotBlank(menu.getMenuName())) {
            queryWrapper.lambda().like(Menu::getMenuName, menu.getMenuName());
        }
        if (menu.getParentId() != null) {
            queryWrapper.lambda().eq(Menu::getParentId, menu.getParentId());
        }
        queryWrapper.lambda().eq(Menu::getType, menu.getType());
        // 处理排序字段
        SortUtil.handlePageSort(commonRequest, page);
        IPage<Menu> result = this.page(page, queryWrapper);
        resultMap.put("rows", result.getRecords());
        resultMap.put("total", result.getTotal());
        return resultMap;
    }

    @Override
    public List<AuthVO> listTreeMenus() {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Menu::getType, 0).orderByAsc(Menu::getSort);
        List<Menu> menuList = this.list(queryWrapper);
        return convertTree(menuList, SystemConstant.MENU_PARENT_ID);
    }

    @Override
    public List<AuthVO> listTreeAuths() {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Menu::getStatus, 1).orderByAsc(Menu::getSort);
        List<Menu> menuList = this.list(queryWrapper);
        return convertTree(menuList, SystemConstant.MENU_ROOT_ID);
    }

    /**
     * @param menuList:菜单列表
     * @param pid:父级菜单ID
     * @return List<AuthVO>
     * @author tom
     * @description 菜单转树结构
     * @createDate 2022/11/18 15:01
     */
    private List<AuthVO> convertTree(List<Menu> menuList, Integer pid) {
        List<AuthVO> result = new ArrayList<>();
        for (Menu menu : menuList) {
            AuthVO authVo = new AuthVO();
            authVo.setId(menu.getId());
            authVo.setName(menu.getMenuName());
            authVo.setType(menu.getType());
            authVo.setStatus(menu.getStatus());

            Integer menuId = menu.getId();
            Integer parentId = menu.getParentId();
            if (parentId != null) {
                if (parentId.equals(pid)) {
                    //递归查询当前子菜单的子菜单
                    List<AuthVO> authVoList = convertTree(menuList, menuId);
                    authVo.setChildren(authVoList);
                    result.add(authVo);
                }
            }
        }
        return result;
    }
}
